package com.gzxx.util;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gaopd
 * @date 2020/7/22 10:48 上午
 */
public class GsonUtil {

    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /**
     * Object to Json
     * @param obj parse Object
     * @return String
     */
    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    /**
     * Json to Object
     * @param json json
     * @param clazz class
     * @param <T> T
     * @return Class Object
     */
    public static<T> T fromJson(String json, Class<T> clazz) {
        return gson.fromJson(json, clazz);
    }

    /**
     * 转成Map的
     * @param gsonString
     * @param <T>
     * @return
     */
    public static <T> Map<String, T> gsonToMaps(String gsonString) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }


    /**
     * List
     * @param gsonString
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> List<T> gsonToList(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }

}
